import os
import time
import requests
from lxml import etree



class carDesktop:
    def __init__(self):
        self.carURL = "https://www.enterdesk.com/zhuomianbizhi/sheying/"



    def Html(self, number: 'str/int'):
        url = self.carURL + str(number) + ".html"
        response = requests.get(url).content.decode('utf-8')
        return response

    def parser(self, html):
        imgURLalt = []
        Html = etree.HTML(html)
        imgSrc = Html.xpath("/html/body/div[13]/div[1]//div/dl/dd/a/img/@src")
        imgAlt = Html.xpath("/html/body/div[13]/div[1]//div/dl/dd/a/img/@alt")
        imgURLalt.append(imgSrc)
        imgURLalt.append(imgAlt)
        return imgURLalt

    def Download(self, ImgURLalt):
        path = "Img"
        if not os.path.exists(path):  # 看是否有该文件夹，没有则创建文件夹
            os.mkdir(path)
        for i in range(len(ImgURLalt[0])):
            url = ImgURLalt[0][i]
            alt = ImgURLalt[1][i]
            start = time.time()  # 下载开始时间
            response = requests.get(url, stream=True)  # stream=True必须写上
            size = 0  # 初始化已下载大小
            chunk_size = 1024  # 每次下载的数据大小
            content_size = int(response.headers['content-length'])  # 下载文件总大小
            try:
                if response.status_code == 200:  # 判断是否响应成功
                    print('Start download,[File size]:{size:.2f} MB'.format(
                        size=content_size / chunk_size / 1024))  # 开始下载，显示下载文件大小
                    filepath = path + '\\{}.jpg'.format(alt)  # 设置图片name，注：必须加上扩展名
                    with open(filepath, 'wb') as file:  # 显示进度条
                        for data in response.iter_content(chunk_size=chunk_size):
                            file.write(data)
                            size += len(data)
                            print('\r' + '[%s下载进度]:%s%.2f%%' % (
                            alt, '>' * int(size * 50 / content_size), float(size / content_size * 100)), end=' ')
                end = time.time()  # 下载结束时间
                print('Download completed!,times: %.2f秒' % (end - start))  # 输出下载用时时间
            except:
                print("Error")
if __name__ == '__main__':

    app = carDesktop()
    for i in range(50):
        html = app.Html(i)
        Img = app.parser(html)
        app.Download(Img)